﻿using CuoDing.Core.DAL;
using CuoDing.Core.Model;
using CuoDing.Core.Model.Enum;
using CuoDing.Core.Model.Model;
using CuoDing.Core.Model.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CuoDing.Core.BLL
{
    public class SystemOperateLogBLL : ISystemOperateLogBLL
    {
        private readonly SystemOperateLogDAL _dal; 
        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="dal"></param>
        public SystemOperateLogBLL(SystemOperateLogDAL dal)
        {
            _dal = dal;
        }

        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<DXResult> AddLog(SystemOperateLog model)
        {
            DXResult dXResult = new DXResult();

            int i = await _dal.UpdateOrInsert(model);
            if (i > 0)
            {
                dXResult.code = DXCode.Success;
            }
            else
                dXResult.code = DXCode.Failure;
            return dXResult;
        }
        /// <summary>
        /// 获取日志
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<SystemOperateLog> GetUser(long id)
        {
            SystemOperateLog dXResult = await _dal.GetById(id);
            return dXResult;
        }


        /// <summary>
        /// 更新日志（事务）
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public DXResult Update(SystemOperateLog item)
        {
            DXResult dXResult = new DXResult();

            try
            {
                //注意：Transaction不支持异步编程
                _dal.fsql.Transaction(() =>
                {
                    item.ModifyTime = DateTime.Now;
                    //更新日志表
                    dXResult.count = _dal.fsql.Update<SystemOperateLog>().SetSource(item)
                        .IgnoreColumns(it => new { it.CreateTime })
                        .ExecuteAffrows();
                    //更新其他关联表
                    _dal.fsql.Ado.ExecuteNonQuery(string.Format("UPDATE TEST_USER SET ModifyTime=sysdate WHERE USERID='{0}'", item.Id));

                    if (dXResult.count < 1)
                        throw new Exception("数据修改失败");
                    dXResult.code = DXCode.Success;
                    dXResult.msg = "数据已修改";
                });
            }
            catch (Exception ex)
            {
                dXResult.code = DXCode.Failure;
                dXResult.msg = ex.Message;
            }

            return dXResult;
        }
    }
}
